package com.itboye.ihomebank.activity.key;

import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.bigkoo.pickerview.TimePickerView;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.SIDBean;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.interfaces.IRefreshAfterAlert;
import com.itboye.ihomebank.presenter.KeyPresenter;
import com.itboye.ihomebank.presenter.KeyTwoPresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.TimesUtils;
import com.itboye.ihomebank.util.UIAlertViewTwo;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;

/**
 * 发送钥匙
 *
 */
public class ActivitySendKey extends BaseOtherActivity implements Observer{
	View v_statusbar;
	ImageView send_key_finish;// 返回
	RelativeLayout send_key_xuanze;// 选择钥匙类型
	TextView send_key_xuan;// 钥匙类型
	LinearLayout send_key_kuang;// 选择框

	LinearLayout send_layout01;// 永久钥匙时候的界面
	EditText send_yaoshi, send_beizhu;// 永久钥匙时候的界面(住家账号,备注)
	TextView send_ok01;// 永久钥匙时候的界面(发送)

	LinearLayout send_layout02;// 期限钥匙时候的界面
	EditText send_yaoshi02, send_beizhu02;// 期限钥匙时候的界面(住家账号,备注)
	TextView send_start_time, send_stop_time;// 期限钥匙时候的界面(开始时间，结束时间)
	TextView send_ok02;// 期限钥匙时候的界面(发送)

	PopupWindow popupWindow;
	UserPresenter userPresenter;
	private String lockId;
	private String uid;
	private String toUid;
	private String mark;
	
	long startT,endT;
	long currentTime;

	LinearLayout kaishi_time,jieshu_time;
	TextView kaishi_time_tv,jieshu_time_tv;
	private TimePickerView pvCustomTimeStart,pvCustomTimeEnd;
	long startDate;

	long start,end;
	UIAlertViewTwo uiAlertViewTwo;
	KeyPresenter keyPresenter;
	String type="";//标志是什么类型的用户跳过来的，admin管理员（可以发租户钥匙和普通钥匙），rent租户（只能发租户用户钥匙）。
	String send_type="1";//发送的钥匙类型{管理员发送(1用户/2租户),租户发送(3租户用户)}
	private int cz;
	@Override
	public void onClick(View v) {
		uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
		switch (v.getId()) {
		case R.id.send_key_finish:
			finish();
			break;
		case R.id.send_key_xuan:
		case R.id.send_key_xuanze:
			PuPoWindow(v);
			break;
		case R.id.send_key_yongjiu:// 永久钥匙
			popupWindow.dismiss();
			send_key_xuan.setText("永久");
			send_layout01.setVisibility(View.VISIBLE);
			send_layout02.setVisibility(View.GONE);

			break;
		case R.id.send_key_qixian:// 期限钥匙
			popupWindow.dismiss();
			send_key_xuan.setText("期限");
			send_layout01.setVisibility(View.GONE);
			send_layout02.setVisibility(View.VISIBLE);
			break;
		case R.id.send_ok01:// 永久
			cz=1;
			String sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
			if(send_yaoshi.getText().toString().equals("")){
				ByAlert.alert("请输入对方账号");
			}
			showProgressDialog("请稍后...", true);
			String touid = send_yaoshi.getText().toString();
			mark = send_beizhu.getText().toString();
			lockId = getIntent().getStringExtra("lockid");
			if ("".equals(sid)){
				userPresenter.sendKey(uid, touid, lockId, "0", "0", mark,send_type);
			}else {

				userPresenter.sendKey(sid, touid, lockId, "0", "0", mark,send_type);
			}

			break;
		case R.id.send_ok02:
			cz=2;
			String sid1=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";

			if(send_yaoshi02.getText().toString().equals("")){
				ByAlert.alert("请输入对方账号");
			}
			if(!send_start_time.getText().toString().equals("")&&!send_stop_time.getText().toString().equals("")){
				if (endT <= startT) {
					ByAlert.alert("结束时间应该大于开始时间");
					return;
				}
				if (currentTime > endT) {
					ByAlert.alert("结束时间应该大于当前时间");
					return;
				}
			}
			showProgressDialog("请稍后...", true);
			mark = send_beizhu02.getText().toString();
			String toUid = send_yaoshi02.getText().toString();
			lockId = getIntent().getStringExtra("lockid");
			if ("".equals(sid1)){
				userPresenter.sendKey(uid, toUid, lockId, startT/1000+"", endT/1000+"", mark,send_type);
			}else {
				userPresenter.sendKey(sid1, toUid, lockId, startT/1000+"", endT/1000+"", mark,send_type);

			}
			break;
		case R.id.kaishi_time:
		case R.id.kaishi_time_tv:
		case R.id.send_start_time:
			pvCustomTimeStart.show();
			break;
		case R.id.jieshu_time:
		case R.id.jieshu_time_tv:
		case R.id.send_stop_time:
			pvCustomTimeEnd.show();
			break;
		default:
			break;
		}
	}

	@Override
	protected int layout_id() {
		// TODO Auto-generated method stub
		return R.layout.activity_send_key;
	}

	@Override
	protected void onInitController() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onInit() {
		// TODO Auto-generated method stub
		setStatusBarHeight(v_statusbar);

		uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
		lockId = getIntent().getStringExtra("lockid");
		type = getIntent().getStringExtra("type");
		start= getIntent().getLongExtra("start",0);
		end= getIntent().getLongExtra("end",0);
		keyPresenter=new KeyPresenter(this);

		if (type.equals("0")){
			uiAlertViewTwo=new UIAlertViewTwo(this,"租客管理员","普通用户","取消");
			uiAlertViewTwo.show();
			uiAlertViewTwo.setClicklistener(new UIAlertViewTwo.ClickListenerInterface() {
				@Override
				public void doOne() {
					uiAlertViewTwo.dismiss();
//					showProgressDialog("正在获取租户信息，请稍后......",false);
//					keyPresenter.onRentInfo(uid,lockId);
					send_layout01.setVisibility(View.GONE);
					send_layout02.setVisibility(View.VISIBLE);
					send_key_xuanze.setVisibility(View.GONE);
					send_type="2";
				}

				@Override
				public void doTwo() {
					uiAlertViewTwo.dismiss();
					send_type="1";
				}

				@Override
				public void doThree() {
					uiAlertViewTwo.dismiss();
					send_type="1";
				}
			});

		}else{
			send_type="3";//租户只能给普通用户发租户钥匙
			send_key_xuan.setText("期限");
			send_key_xuanze.setVisibility(View.GONE);
			send_layout01.setVisibility(View.GONE);
			send_layout02.setVisibility(View.VISIBLE);
			startT=start*1000;
			send_start_time.setText(TimesUtils.timeStamp2Date(start)+"");
			endT=end*1000;
			send_stop_time.setText(TimesUtils.timeStamp2Date(end)+"");
		}

		userPresenter = new UserPresenter(this);
		currentTime = System.currentTimeMillis();
		initTimePickerStart();
		initTimePickerEnd();
	}

	@Override
	protected void onReadIntent(Bundle bundle) {
		// TODO Auto-generated method stub

	}

	/**
	 * 钥匙搜索切换框
	 * @param v
	 */
	private void PuPoWindow(View v) {
		View view = LayoutInflater.from(this).inflate(
				R.layout.item_yaoshi_qiehuan, null);
		TextView send_key_yongjiu = (TextView) view
				.findViewById(R.id.send_key_yongjiu);
		TextView send_key_qixian = (TextView) view
				.findViewById(R.id.send_key_qixian);

		send_key_yongjiu.setOnClickListener(this);
		send_key_qixian.setOnClickListener(this);
		popupWindow = new PopupWindow(view, LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.showAsDropDown(v);
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == UserPresenter.sendKey_success) {
				ByAlert.alert(entity.getData());
				finish();
			} else if (entity.getEventType() == UserPresenter.sendKey_fail) {
				if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
					//切换 锁备用服务器
					showAlert();
				}else {
					ByAlert.alert(entity.getData());
				}
			} else if (entity.getEventType()==UserPresenter.By_GETSID_success){//获取sid 成功
				SIDBean data1 = (SIDBean) entity.getData();
				SPUtils.put(MyApplcation.ctx,null, SPContants.LOCK_SESSION,data1.getSid());
				SPUtils.put(MyApplcation.ctx,null,SPContants.ISLOCK,true);
				toRefreshData();
			}else if (entity.getEventType()==UserPresenter.By_GETSID_fail){
				ByAlert.alert(entity.getMsg());
			}
		}
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	private void initTimePickerStart() {
		/**
		 * @description
		 *
		 * 注意事项：
		 * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
		 * 具体可参考demo 里面的两个自定义layout布局。
		 * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
		 * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
		 */
		Calendar selectedDate = Calendar.getInstance();//系统当前时间
		Calendar startDate = Calendar.getInstance();
		startDate.set(2017, 1, 23);
		final Calendar endDate = Calendar.getInstance();
		endDate.set(2027, 2, 28);
		//时间选择器 ，自定义布局
		pvCustomTimeStart = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
			@Override
			public void onTimeSelect(Date date, View v) {//选中事件回调
				if (type.equals("0")){//管理员
					send_start_time.setText(getTime(date));
					startT =  TimesUtils.getStringToDateTwo02(getTime(date));
				}else { //租客
					String startString=TimesUtils.timeStamp2Date(start)+"";
					String endString=TimesUtils.timeStamp2Date(end)+"";
					if (date.getTime()<start*1000){
						ByAlert.alert("开始时间不得少于"+startString);
						return;
					}

					if (date.getTime()>end*1000){
						ByAlert.alert("开始时间不得大于"+endString);
						return;
					}
					send_start_time.setText(getTime(date));
					startT =  TimesUtils.getStringToDateTwo02(getTime(date));
				}


			}
		})
				.setDate(selectedDate)
				.setRangDate(startDate, endDate)

				.setType(new boolean[]{true, true, true, true, false, false})
				.setLabel("年", "月", "日", "时", "", "")
				.isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
				.setDividerColor(0xFF24AD9D)
				.build();
	}
	private void initTimePickerEnd() {
		/**
		 * @description
		 *
		 * 注意事项：
		 * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
		 * 具体可参考demo 里面的两个自定义layout布局。
		 * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
		 * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
		 */
		Calendar selectedDate = Calendar.getInstance();//系统当前时间
		Calendar startDate = Calendar.getInstance();
		startDate.set(2017, 1, 23);
		Calendar endDate = Calendar.getInstance();
		endDate.set(2027, 2, 28);
		//时间选择器 ，自定义布局
		pvCustomTimeEnd = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
			@Override
			public void onTimeSelect(Date date, View v) {//选中事件回调
				if (type.equals("0")) {//管理员
					send_stop_time.setText(getTime(date));
					endT =  TimesUtils.getStringToDateTwo02(getTime(date));

				}else {

					String startString=TimesUtils.timeStamp2Date(start)+"";
					String endString=TimesUtils.timeStamp2Date(end)+"";
					if (date.getTime()<start*1000){
						ByAlert.alert("结束时间不得少于"+startString);
						return;
					}

					if (date.getTime()>end*1000){
						ByAlert.alert("结束时间不得大于"+endString);
						return;
					}
					send_stop_time.setText(getTime(date));
					endT =  TimesUtils.getStringToDateTwo02(getTime(date));
				}


			}
		})
				.setDate(selectedDate)
				.setRangDate(startDate, endDate)

				.setType(new boolean[]{true, true, true, true, false, false})
				.setLabel("年", "月", "日", "时", "", "")
				.isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
				.setDividerColor(0xFF24AD9D)
				.build();

	}
	private String getTime(Date date) {//可根据需要自行截取数据显示
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:00");
		return format.format(date);
	}


	private void toRefreshData() {
		String sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
		switch (cz){
			case 1:
				String touid = send_yaoshi.getText().toString();
				mark = send_beizhu.getText().toString();
				lockId = getIntent().getStringExtra("lockid");
				if ("".equals(sid)){
					userPresenter.sendKey(uid, touid, lockId, "0", "0", mark,send_type);
				}else {

					userPresenter.sendKey(sid, touid, lockId, "0", "0", mark,send_type);
				}
				break;
			case 2:
				mark = send_beizhu02.getText().toString();
				String toUid = send_yaoshi02.getText().toString();
				lockId = getIntent().getStringExtra("lockid");
				if ("".equals(sid)){
					userPresenter.sendKey(uid, toUid, lockId, startT/1000+"", endT/1000+"", mark,send_type);
				}else {
					userPresenter.sendKey(sid, toUid, lockId, startT/1000+"", endT/1000+"", mark,send_type);

				}
				break;
		}
	}
}
